<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
          <!-- 用一个行列布局 -->
          <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
            <el-col :span="20">
              <span>江苏传智播客教育科技股份有限公司</span>
            </el-col>
            <el-col :span="4">
              <el-row type="flex" justify="end">
                <!-- 两个内容 -->
                <el-col>负责人</el-col>
                <el-col>操作</el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-tree
            :data="list"
            :props="defaultProps"
            :default-expand-all="true"
          >
            <!-- 作用域插槽 data拿到的是每一个子节点的对象 -->
            <template #default="{ data }">
              <el-row
                type="flex"
                justify="space-between"
                align="middle"
                style="height: 40px; width: 100%;"
              >
                <el-col :span="20">
                  <span>{{ data.name }}</span>
                </el-col>
                <el-col :span="4">
                  <el-row type="flex" justify="end">
                    <!-- 两个内容 -->
                    <el-col>{{ data.manager }}</el-col>
                    <el-col>
                      <!-- 下拉菜单 element -->
                      <el-dropdown>
                        <span> 操作<i class="el-icon-arrow-down" /> </span>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item @click.native="openAddDialog(data.id)">添加子部门</el-dropdown-item>
                          <el-dropdown-item @click.native="editDepart(data.id)">编辑部门</el-dropdown-item>
                          <!-- 在vue组件中使用事件必须添加native修饰符，否则不起作用 -->
                          <!-- 传入获取到的id -->
                          <el-dropdown-item @click.native="delPart(data.id)">删除部门</el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-tree>
      </el-card>
      <template>
        <el-dialog
          title="提示"
          :visible="addVisible"
          width="30%"
          @close="closeAddDialog"
        >
          <!-- 新增部门的弹层 -->
            <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
              <el-form-item label="部门名称" prop="name">
                <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
              </el-form-item>
              <el-form-item label="部门编码" prop="code">
                <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
              </el-form-item>
              <el-form-item label="部门负责人" prop="manager">
                <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
                  <el-option 
                    v-for="item in managerList" 
                    :key="item.id" 
                    :value="item.username" 
                    :label="item.username" 
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="部门介绍" prop="introduce">
                <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea"/>
              </el-form-item>
            </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addVisible = false">取 消</el-button>
            <el-button type="primary" @click="clickSubmit">确 定</el-button>
          </span>
        </el-dialog>
      </template>
    </div>
  </div>
</template>

<script>
import { getDepartments, delDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/department'
import  { getEmployeeSimple } from '@/api/employees'
import transTree from '@/utils/transTree'
export default ({
  data() {
    // const validateCode = (rule, value, callback) => {
    //   let codeList = this.allList.map(item => item.code)
    //   if (codeList.includes(value)) {
    //     return callback(new Error('当前code码重复'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      list: [{
        name: '财务部',
        children: [
          {
            name: '财务核算部'
          },
          {
            name: '税务核算部'
          }
        ]
      }],
      allList: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      addVisible: false,
      // 添加弹窗数据
      form: {
          name: '', // 部门名称
          code: '', // 部门编码
          manager: '', // 部门管理者
          introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          // { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change']}
        ]
      },
      // 弹窗下拉菜单数据
      managerList: [],
      curId: ''
    }
  },
  methods: {
    async fetchDepartment() {
      const { depts } = await getDepartments()
      this.list = transTree(depts)
      this.allList = depts
    },
    // 删除部门选项
    delPart(id) {
      this.$confirm('您确定进行删除么, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delDepartments(id)
        this.$message.success('删除部门成功')
        this.fetchDepartment()
      }).catch(() => {})
    },
    // 打开弹框
    openAddDialog(id) {
      this.addVisible = true
      this.curId = id
    },
    // 关闭弹框
    closeAddDialog() {
      this.addVisible = false
      this.$refs.deptForm.resetFields()
    },
    // 获取负责人数据
    async fetchManagerList() {
      const data = await getEmployeeSimple()
      this.managerList = data
    },
    // 兜底校验
    clickSubmit() {
      this.$refs.deptForm.validate(async valid => {
        if(valid) {
          if (this.form.id) {
            await updateDepartments(this.form)
          } else {
            await addDepartments({...this.form, pid: this.curId})
          }
          this.addVisible = false
          this.fetchDepartment()
          this.$message.success(`${this.form.id ? '修改成功' : '添加成功'}`)
          this.$refs.deptForm.resetFields()
        }
      })
    },
    // async fetchDepartmentList() {
    //   const res = await getDepartment()
    //   // 把一个平铺的数组先处理成组件要求的tree型结构 然后再交给响应式的数据
    //   this.list = transTree(res.depts)
    //   // 存一份原始 平铺的未经过处理的数据
    //   this.sourceList = res.depts
    // }
    // 编辑部门资料
    async editDepart(id) {
      // 数据回填
      this.addVisible = true
      const res = await getDepartDetail(id)
      this.form = res
      console.log(this.form.id)
    }
    // confirmAdd() {
    //   // 先进行兜底校验
    //   this.$refs.deptForm.validate(async(valid) => {
    //     if (valid) {
    //       if (this.form.id) {
    //         // 调用更新接口
    //         await updateDepartments(this.form)
    //       } else {
    //         // 调用新增接口
    //         await addDepartments({ ...this.form, pid: this.curId })
    //       }
    //     }
    //   })
    // }
  },
  mounted() {
    this.fetchDepartment()
    this.fetchManagerList()
  }
})
</script>
